﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace common.net
{
    public class address
    {
        public static System.Net.IPAddress GetWindowFromIP(int index)
        {
            string hostname;
            System.Net.IPHostEntry localhost;
            System.Net.IPAddress localaddr;

            hostname = System.Net.Dns.GetHostName();
            localhost = System.Net.Dns.GetHostByName(hostname);
            localaddr = localhost.AddressList[index]; //localaddr中就是本机ip地址
            return localaddr;
        }

        public static string get_in_IP()
        {
            return GetWindowFromIP(0).ToString();
        }
    }

    public class Router
    {
        private Encoding gb2312 = Encoding.GetEncoding(936);

        //路由器的web管理系统默认编码为gb2312
        /// <summary>
        /// 使用HttpWebRequest对象发送请求
        /// /// </summary>
        /// /// <param name="url"></param>
        /// /// <param name="encoding">编码</param>
        /// /// <param name="cache">凭证</param>
        /// /// <returns></returns>
        private static string SendRequest(string url, Encoding encoding, CredentialCache cache)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            if (cache != null)
            {
                request.PreAuthenticate = true;
                request.Credentials = cache;
            }
            string html = null;
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader srd = new StreamReader(response.GetResponseStream(), encoding);
                html = srd.ReadToEnd();
                srd.Close();
                response.Close();
            }
            catch (Exception ex)
            { html = "FALSE" + ex.Message; }
            return html;
        }

        /// <summary>
        /// 获取路由MAC和外网IP地址
        /// /// </summary>
        /// /// <param name="RouterIP">
        /// 路由IP地址，就是网关地址了，默认192.168.1.1</param>
        /// /// <param name="UserName">用户名</param>
        /// /// <param name="Passowrd">密码</param>
        /// /// <returns></returns>
        private string LoadMACWanIP(string RouterIP, string UserName, string Passowrd)
        {
            CredentialCache cache = new CredentialCache();
            string url = "http://" + RouterIP + "/userRpm/StatusRpm.htm";
            cache.Add(new Uri(url), "Basic", new NetworkCredential(UserName, Passowrd));
            return SendRequest(url, gb2312, cache);
        }

        public string getWanIP()
        {
            string all = LoadMACWanIP("192.168.1.1", "admin", "admin");
            string str = "";
            //char[] ch = { '[', ']' };
            //System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(str, @"\[(?<IP>[0-9\.]*)\]");
            //return m.Value.Trim(ch);

            int start = all.IndexOf("wanPara") + 1;
            var tempip = all.Substring(start, 100);

            //var ss = Regex.Match(tempip, @"^\d+.\d+.\d+.\d+$");

            var s1 = tempip.Replace("\"", "");
            foreach (var item in s1.Split('\n'))
            {
                //System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(item, @"^\d+\.\d+\.\d+\.\d+$");
                System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(item, @"\d+\.\d+\.\d+\.\d+");

                if (m.Success)
                {
                    //this.richTextBox1.Text = m.Value;
                    str = m.Value;
                    return str;
                }
            }

            return str;
        }
    }

    ///// <summary>
    ///// IP地址服务类
    ///// </summary>
    //public class IPHelper
    //{
    //    HttpContextBase context;
    //    /// <summary>
    //    /// 构造函数
    //    /// </summary>
    //    /// <param name="httpContext">请求上下文</param>
    //    public IPHelper(HttpContextBase httpContext)
    //    {
    //        context = httpContext as HttpContextBase;
    //    }

    //    /// <summary>
    //    /// ip正则校验
    //    /// </summary>
    //    private Regex RegIP
    //    {
    //        get { return new Regex(@"^\d+.\d+.\d+.\d+$"); }
    //    }

    //    /// <summary>
    //    /// 获取ip地址
    //    /// </summary>
    //    /// <returns></returns>
    //    public string GetIpAddress()
    //    {
    //        string ipAdress = "172.0.0.1";
    //        if (RegIP.IsMatch(GetClientIpPv6()))
    //        {
    //            ipAdress = GetClientIpPv6();
    //        }
    //        if (RegIP.IsMatch(GetClientIPv4()))
    //        {
    //            ipAdress = GetClientIPv4();
    //        }
    //        return ipAdress;
    //    }

    //    /// <summary>
    //    /// 判断客户端有没有使用代理使用代理返回true,没有使用代理返回false
    //    /// </summary>
    //    /// <returns></returns>
    //    private bool IsProxy()
    //    {
    //        return context.Request.ServerVariables["HTTP_VIA"] != null;
    //    }

    //    /// <summary>
    //    /// 获取客户端的IPv6如果获取不到IPv6将自动获取IPv4
    //    /// </summary>
    //    /// <returns></returns>
    //    private string GetClientIpPv6()
    //    {
    //        string ipv6 = string.Empty;
    //        //ipv6 = Request.UserHostAddress;
    //        if (IsProxy())//客户端有使用代理
    //        {
    //            ipv6 = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    //        }
    //        else//客户端没有使用代理
    //        {
    //            ipv6 = context.Request.ServerVariables["REMOTE_ADDR"].ToString();
    //        }
    //        return ipv6;
    //    }

    //    /// <summary>
    //    /// 获取客户端的IPv4
    //    /// </summary>
    //    /// <returns></returns>
    //    private string GetClientIPv4()
    //    {
    //        string ipv4 = String.Empty;
    //        foreach (IPAddress IPA in Dns.GetHostAddresses(context.Request.UserHostAddress))
    //        {
    //            if (IPA.AddressFamily.ToString() == "InterNetwork")
    //            {
    //                ipv4 = IPA.ToString();
    //                break;
    //            }
    //        }
    //        if (ipv4 != String.Empty)
    //        {
    //            return ipv4;
    //        }
    //        foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
    //        {
    //            if (IPA.AddressFamily.ToString() == "InterNetwork")
    //            {
    //                ipv4 = IPA.ToString();
    //                break;
    //            }
    //        }
    //        return ipv4;
    //    }
    //}
}